package com.myproject.utils;

import java.io.*;

public class FileUtils {

    /*
    * 文件夹 /abc/123/456.txt
    * 参数 /abc  /def
    * 结果 /def/123/456.txt

    * */
    public void copyDir(String sourPath,String descPath){

        File file = new File(sourPath);
        if (file.isFile()){
            copyFile(sourPath,descPath,true);
        }

        if (file.isDirectory()){
            //创建目标目录
            File dir = new File(descPath);
            if (!dir.isDirectory()){
                dir.mkdirs();
            }
            File[] files = file.listFiles();
            for (File subFile:files){

                String targetPath = descPath + File.separator + file.getName();
                copyDir(subFile.getAbsolutePath(),targetPath);

            }
        }
    }

    /*
     * 文件拷贝,目标路径上级目录不存在会自动创建
     * */
    public static void copyFile(String from,String to,boolean keepOriginTime){


        //校验上级目录是否存在，如不存在则创建
        String destDir = getDir(to);
        File dirFile = new File(destDir);
        if (!dirFile.isDirectory()){
            dirFile.mkdirs();
        }

        //拷贝文件
        try {
            InputStream inputStream = new FileInputStream(from);
            OutputStream outputStream = new FileOutputStream(to);
            byte[] bytes = new byte[100];
            int i;
            while ((i=inputStream.read(bytes))!=-1){
                outputStream.write(bytes);
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e){
            throw new RuntimeException(e);
        }

        //是否保持拷贝文件原有更新时间
        if (keepOriginTime){
            File orgFile = new File(from);
            File file = new File(to);
            file.setLastModified(orgFile.lastModified());
        }

    }

    public static String getDir(String path){

        if (path.contains(File.separator)){

            int index = path.lastIndexOf(File.separator);
            String dir = path.substring(0,index);
            return dir;
        }

        if (path.contains("/")){

            int index = path.lastIndexOf("/");
            String dir = path.substring(0,index);
            return dir;
        }

        return null;
    }
}
